package com.ccteam.fluidmusic.ui.local

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.FragmentNavigatorExtras
import androidx.navigation.fragment.findNavController
import com.ccteam.fluidmusic.ui.PARENT_ID_KEY
import com.ccteam.fluidmusic.R
import com.ccteam.fluidmusic.databinding.FragmentLocalAlbumPagerBinding
import com.ccteam.fluidmusic.view.adapters.AlbumListItemAdapter
import com.ccteam.fluidmusic.view.base.LightBounceEdgeEffectFactory
import com.ccteam.fluidmusic.view.bean.LoadMessage
import com.ccteam.model.Resource
import com.ccteam.shared.result.album.AlbumDetailHeaderItem
import com.ccteam.shared.result.album.AlbumListItem
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject

/**
 * @author Xiaoc
 * @since 2021/1/7
 *
 * 本地专辑页面显示
 * 与 [LocalMusicViewModel] 联动
 * 显示本地专辑的列表信息
 * 此Fragment显示在 [ViewPager2] 中
 */
@AndroidEntryPoint
class LocalAlbumPagerFragment : Fragment() {

    private lateinit var parentId: String

    private var _binding: FragmentLocalAlbumPagerBinding? = null
    private val binding get() = _binding!!

    private var isFirstLoad: Boolean = true

    private val localMusicViewModel by viewModels<LocalMusicViewModel>(ownerProducer = { parentFragment ?: this })

    @Inject lateinit var lightBounceEdgeEffectFactory: LightBounceEdgeEffectFactory

    private val localMusicAlbumClickCallback = object : AlbumListItemAdapter.AlbumListItemCallback {

        override fun onClickItem(view: View, albumItem: AlbumListItem) {
            // 设置过渡动画
            val musicListDetailTransitionName = getString(R.string.local_music_list_detail_transition_name)
            val extra = FragmentNavigatorExtras(view to musicListDetailTransitionName)

            findNavController().navigate(LocalMusicFragmentDirections
                .actionLocalMusicFragmentToLocalMusicListFragment(
                    albumItem.mediaId,
                    AlbumDetailHeaderItem(albumItem.albumId,albumItem.albumTitle,
                        albumItem.albumArtUri, albumItem.artist, albumItem.year,
                        null,albumItem.artistId ?: "-1")
                ),extra)
        }

    }

    private val adapter = AlbumListItemAdapter(localMusicAlbumClickCallback)

    companion object {
        @JvmStatic
        fun newInstance(parentId: String): LocalAlbumPagerFragment {
            return LocalAlbumPagerFragment().apply {
                arguments = Bundle().apply {
                    putString(PARENT_ID_KEY, parentId)
                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
        if(isFirstLoad){
            observeAlbumItems()
            isFirstLoad = false
        }
    }

    private fun observeAlbumItems(){
        // 观察列表变化，有变化则提交，如果处于加载中，则显示进度条
        localMusicViewModel.albumItems.observe(viewLifecycleOwner, {
            if(it is Resource.Success){
                adapter.submitList(it.data)
            }
        })
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentLocalAlbumPagerBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        parentId = arguments?.getString(PARENT_ID_KEY) ?: return

        lightBounceEdgeEffectFactory.applyBounceView(binding.rvLocalAlbumPagerList,this)
        binding.rvLocalAlbumPagerList.edgeEffectFactory = lightBounceEdgeEffectFactory

        binding.rvLocalAlbumPagerList.adapter = adapter

        localMusicViewModel.rescanStatusByTab.observe(viewLifecycleOwner, {
            // 如果当前parentId处于未扫描状态，则开始订阅，否则不订阅，防止重复订阅
            if(it[parentId] == LocalMusicViewModel.RESCAN_NONE){
                // 订阅前显示进度条
                binding.statusView.changeToLoadingStatus(true)
                localMusicViewModel.subscribeByChildrenParentId(parentId)
            }
        })

        localMusicViewModel.albumLoadMessage.observe(viewLifecycleOwner, {
            binding.statusView.changeToLoadingStatus(it is LoadMessage.Loading)
            binding.statusView.changeToErrorStatus(it)
        })

    }

    override fun onDestroyView() {
        super.onDestroyView()
        isFirstLoad = true
        _binding = null
    }
}